<template>
  <el-form
    :model="from"
    status-icon
    :rules="rules"
    ref="from"
    label-width="100px"
    class="login-form"
    key="login"
  >
    <el-form-item label="邮箱" prop="email">
      <el-input type="email" v-model="from.email" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input
        type="password"
        v-model="from.password"
        autocomplete="off"
      ></el-input>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        :disabled="isLoading"
        @click="submitForm('from')"
        >{{ isLoading ? "提交中..." : "提交" }}</el-button
      >
      <el-button @click="resetForm('from')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { loginFetch } from "@/api/login.js";
import { setCookies } from "@/utils";
import { mapState } from "vuex";

export default {
  data() {
    let emailRex = new RegExp(
      "^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$"
    );
    let email = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入邮箱"));
      } else {
        // 判断输入的内容是否符合正则表达式
        if (emailRex.test(value)) {
          callback();
        } else {
          this.$refs.from.validateField("pass");
          callback(new Error("请正确输入邮箱"));
        }
      }
    };

    // 密码验证规则
    let password = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    return {
      from: {
        email: "",
        pass: "",
      },
      rules: {
        email: [{ validator: email, trigger: "blur" }],
        papasswordss: [{ validator: password, trigger: "blur" }],
      },
    };
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    async login() {
      let data = await loginFetch(this.from);
      if (data) {
        setCookies(data);
        this.$store.dispatch("asyncChangeUser", data);
        this.$router.push(
          {
            name: "HomeIndex",
          },
          (err) => {}
        );
      }
      this.$store.commit("changeLoginState", false);
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.login();
        } else {
          return false;
        }
      });
    },
  },
  computed: mapState({
    isLoading: "isLoading",
  }),
};
</script>

<style>
</style>